<template>
  <div class="marketing-video">
    <!-- 顶部进度条 -->
    <div class="progress-bar">
      <div class="step-item active">
        <div class="step-number">1</div>
        <div class="step-text">选择一个数字人并上传一张产品图片</div>
      </div>
      <div class="step-item">
        <div class="step-number">2</div>
        <div class="step-text">编辑营销文案</div>
      </div>
      <div class="step-item">
        <div class="step-number">3</div>
        <div class="step-text">生成视频</div>
      </div>
      <div class="step-item">
        <div class="step-number">4</div>
        <div class="step-text">完成</div>
      </div>
    </div>

    <!-- 主要内容区域 -->
    <div class="main-content">
      <!-- 左侧选择区域 -->
      <div class="left-panel">
        <!-- 分类选择 -->
        <div class="category-tabs">
          <el-tabs v-model="activeCategory" @tab-change="handleTabChange">
            <el-tab-pane 
              v-for="category in categories" 
              :key="category.value" 
              :label="category.label" 
              :name="category.value"
            >
              <div class="avatar-grid" ref="avatarGridRef" @scroll="handleScroll">
                <!-- 上传自己的照片卡片 -->
                <div class="upload-card">
                  <input
                    type="file"
                    accept="image/*"
                    class="file-input"
                    ref="fileInputRef"
                    @change="handleImageSelect"
                  />
                  <div class="upload-content" @click="triggerFileSelect">
                    <el-icon :size="32"><Plus /></el-icon>
                    <span>使用我的照片</span>
                  </div>
                </div>
                <!-- 数字人列表 -->
                <div
                  v-for="avatar in allAvatars"
                  :key="avatar.id"
                  class="avatar-card"
                  :class="{ active: selectedAvatar?.id === avatar.id }"
                  @click="handleSelectAvatar(avatar)"
                >
                  <img :src="avatar.imageUrl" :alt="avatar.name" class="avatar-image" />
                  <div class="avatar-info">
                    <span class="avatar-name">{{ avatar.name }}</span>
                    <el-tag size="small" :type="avatar.gender === 'male' ? 'info' : 'danger'">
                      {{ avatar.gender === 'male' ? '男性' : '女性' }}
                    </el-tag>
                  </div>
                </div>
                <!-- 加载更多提示 -->
                <div v-if="isLoading" class="loading-more">
                  <el-icon class="loading-icon"><Loading /></el-icon>
                  <span>加载中...</span>
                </div>
              </div>
            </el-tab-pane>
          </el-tabs>
        </div>
      </div>

      <!-- 右侧预览区域 -->
      <div class="right-panel">
        <div class="preview-section">
          <h3>预览效果</h3>
          <div class="preview-container">
            <div v-if="!selectedImage?.url" class="upload-placeholder" @click="triggerProductUpload">
              <input
                type="file"
                accept=".jpg,.jpeg,.png,.bmp,.webp"
                class="file-input"
                ref="productFileRef"
                @change="handleProductImageSelect"
              />
              <el-icon :size="48"><Upload /></el-icon>
              <div class="upload-text">上传产品图片</div>
              <div class="upload-hint">支持 JPG、PNG、BMP、WebP 格式</div>
            </div>
            <img v-else :src="selectedImage.url" class="preview-image" />
          </div>
          <div class="action-buttons">
            <el-button v-if="selectedImage" type="danger" @click="resetProductImage">重新上传</el-button>
            <el-button 
              type="primary" 
              :disabled="!canProceed"
              @click="handleNext"
            >
              下一步
            </el-button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { Plus, Upload, Loading } from '@element-plus/icons-vue'
import { ElMessage, ElLoading } from 'element-plus'
import { useRouter } from 'vue-router'
import { apiRequest, API_CONFIG } from '../../config/api.js'
import axios from 'axios'

const router = useRouter()

// 数据
const activeCategory = ref('all')
const selectedAvatar = ref(null)
const selectedImage = ref(null)
const fileInputRef = ref(null)
const productFileRef = ref(null)
const loading = ref(false)
const allAvatars = ref([])
const pageNo = ref(0)
const pageSize = ref(20)
const total = ref(0)
const avatarGridRef = ref(null)
const isLoading = ref(false)
const hasMore = computed(() => allAvatars.value.length < total.value)
const categories = ref([
  { label: 'All', value: 'all', categoryId: '' }
])

// 获取分类列表
const fetchCategories = async () => {
  try {
    const response = await apiRequest('/productAvatar/categoryList', {
      method: 'GET'
    })
    
    if (response.code === 200) {
      // 添加 All 选项
      categories.value = [
        { label: 'All', value: 'all', categoryId: '' },
        ...response.data.map(item => ({
          label: item.categoryName,
          value: item.categoryId,
          categoryId: item.categoryId
        }))
      ]
    } else {
      ElMessage.error(response.message || '获取分类列表失败')
    }
  } catch (error) {
    console.error('获取分类列表失败:', error)
    ElMessage.error('获取分类列表失败')
  }
}

// 获取数字人列表
const fetchAvatarList = async (isLoadMore = false) => {
  if (isLoading.value) return
  isLoading.value = true
  
  try {
    const params = new URLSearchParams({
      pageNo: String(pageNo.value + 1),
      pageSize: String(pageSize.value)
    })

    // 如果不是 all，则添加当前选中分类的 categoryId
    const currentCategory = categories.value.find(cat => cat.value === activeCategory.value)
    if (currentCategory && currentCategory.categoryId) {
      params.append('categoryIds', currentCategory.categoryId)
    }

    const response = await apiRequest(`/productAvatar/resource/avatarList?${params.toString()}`, {
      method: 'GET'
    })
    
    if (response.code === 200) {
      const newAvatars = response.data.data.map(item => ({
        id: item.avatarId,
        name: item.avatarId.slice(0, 8),
        gender: item.gender,
        imageUrl: item.avatarImagePath,
        voiceoverId: item.voiceoverId,
        ethnicityList: item.avatarEthnicityList,
        objectMaskImageInfo: item.objectMaskImageInfo
      }))
      
      if (isLoadMore) {
        allAvatars.value = [...allAvatars.value, ...newAvatars]
      } else {
        allAvatars.value = newAvatars
      }
      
      total.value = response.data.total
    } else {
      ElMessage.error(response.message || '获取数字人列表失败')
    }
  } catch (error) {
    console.error('获取数字人列表失败:', error)
    ElMessage.error('获取数字人列表失败')
  } finally {
    isLoading.value = false
  }
}

// 切换标签时重置页码并重新加载
const handleTabChange = (tab) => {
  console.log('切换标签:', tab)
  activeCategory.value = tab
  pageNo.value = 0
  allAvatars.value = []
  fetchAvatarList()
}

// 处理数字人选择
const handleSelectAvatar = (avatar) => {
  selectedAvatar.value = avatar
}

// 触发文件选择
const triggerFileSelect = () => {
  fileInputRef.value?.click()
}

const triggerProductUpload = () => {
  productFileRef.value?.click()
}

// 处理图片选择
const handleImageSelect = (event) => {
  const file = event.target.files?.[0]
  if (!file) return

  if (!file.type.startsWith('image/')) {
    ElMessage.error('请选择图片文件')
    return
  }

  // 这里应该调用上传接口
  // 暂时使用本地预览
  const reader = new FileReader()
  reader.onload = (e) => {
    selectedImage.value = e.target.result
  }
  reader.readAsDataURL(file)
}

// 处理产品图片选择
const handleProductImageSelect = async (event) => {
  const file = event.target.files?.[0]
  if (!file) return

  if (!file.type.startsWith('image/')) {
    ElMessage.error('请选择图片文件')
    return
  }

  // 获取文件后缀名并转换为对应的格式
  const extension = file.name.split('.').pop()?.toLowerCase()
  let format = 'jpg' // 默认格式

  switch (extension) {
    case 'jpg':
    case 'jpeg':
      format = 'jpg'
      break
    case 'png':
      format = 'png'
      break
    case 'bmp':
      format = 'bmp'
      break
    case 'webp':
      format = 'webp'
      break
    default:
      ElMessage.error('不支持的图片格式，请使用 JPG、PNG、BMP 或 WebP 格式')
      return
  }

  const loading = ElLoading.service({
    lock: true,
    text: '上传中...',
    background: 'rgba(0, 0, 0, 0.7)'
  })

  try {
    // 获取上传凭证
    const uploadResponse = await apiRequest(`${API_CONFIG.ENDPOINTS.GET_UPLOAD_CREDENTIAL}?format=${format}`, {
      method: 'GET'
    })

    if (uploadResponse.code !== 200) {
      throw new Error(uploadResponse.message || '获取上传凭证失败')
    }

    const { uploadUrl, fileId } = uploadResponse.data

    // 上传到S3
    await axios.put(uploadUrl, file, {
      headers: {
        'Content-Type': file.type
      }
    })

    // 保存 fileId 和预览地址
    selectedImage.value = {
      url: uploadUrl.split('?')[0], // 移除查询参数部分
      fileId
    }

  } catch (error) {
    console.error('上传失败:', error)
    ElMessage.error(error.message || '上传失败')
  } finally {
    loading.close()
    if (productFileRef.value) {
      productFileRef.value.value = ''
    }
  }
}

// 重置产品图片
const resetProductImage = () => {
  selectedImage.value = null
  if (productFileRef.value) {
    productFileRef.value.value = ''
  }
}

// 计算属性：是否可以进行下一步
const canProceed = computed(() => {
  return selectedAvatar.value && selectedImage.value?.url
})

// 处理下一步
const handleNext = () => {
  if (!canProceed.value) {
    ElMessage.warning('请选择数字人和上传产品图片')
    return
  }
  
  // 保存当前选择的状态
  localStorage.setItem('marketingAvatar', JSON.stringify(selectedAvatar.value))
  localStorage.setItem('marketingImage', JSON.stringify(selectedImage.value))
  
  // 跳转到下一步
  router.push('/marketing-video/audio')
}

// 处理滚动加载
const handleScroll = async (e) => {
  const { scrollTop, scrollHeight, clientHeight } = e.target
  // 滚动到底部时加载更多
  if (scrollHeight - scrollTop - clientHeight < 50 && !isLoading.value && hasMore.value) {
    console.log('Loading more...', pageNo.value + 1)
    pageNo.value++
    await fetchAvatarList(true)
  }
}

// 在组件挂载时获取分类列表和数字人列表
onMounted(async () => {
  await fetchCategories()
  await fetchAvatarList()
})
</script>

<style scoped>
.marketing-video {
  min-height: 100vh;
  background: #18181c;
  padding: 24px;
  color: #fff;
}

.progress-bar {
  display: flex;
  justify-content: space-between;
  margin-bottom: 40px;
  padding: 0 100px;
}

.step-item {
  display: flex;
  align-items: center;
  gap: 12px;
  position: relative;
  flex: 1;
}

.step-item:not(:last-child)::after {
  display: none;
}

.step-item.active:not(:last-child)::after {
  display: none;
}

.step-number {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background: #2a2a2a;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: bold;
  z-index: 2;
}

.step-item.active .step-number {
  background: #409eff;
}

.step-text {
  color: #909399;
}

.step-item.active .step-text {
  color: #fff;
}

.main-content {
  display: flex;
  gap: 32px;
}

.left-panel {
  flex: 1;
  min-width: 0;
}

.category-tabs {
  margin-bottom: 24px;
}

.avatar-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 20px;
  padding: 20px 0;
  max-height: calc(100vh - 200px); /* 设置最大高度 */
  overflow-y: auto; /* 允许垂直滚动 */
  scrollbar-width: thin;
  scrollbar-color: #409eff #2a2a2a;
}

.avatar-grid::-webkit-scrollbar {
  width: 6px;
}

.avatar-grid::-webkit-scrollbar-track {
  background: #2a2a2a;
  border-radius: 3px;
}

.avatar-grid::-webkit-scrollbar-thumb {
  background: #409eff;
  border-radius: 3px;
}

.loading-more {
  grid-column: 1 / -1;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20px;
  color: #909399;
  gap: 8px;
}

.loading-icon {
  animation: rotating 2s linear infinite;
}

@keyframes rotating {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

.upload-card {
  background: #23232a;
  border-radius: 12px;
  height: 280px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  border: 2px dashed #2a2a2a;
  transition: all 0.3s ease;
}

.upload-card:hover {
  border-color: #409eff;
  background: #2a2a2a;
}

.upload-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 12px;
  color: #909399;
}

.file-input {
  display: none;
}

.avatar-card {
  background: #23232a;
  border-radius: 12px;
  overflow: hidden;
  cursor: pointer;
  transition: all 0.3s ease;
  border: 2px solid transparent;
}

.avatar-card:hover {
  transform: translateY(-5px);
}

.avatar-card.active {
  border-color: #409eff;
}

.avatar-image {
  width: 100%;
  height: 240px;
  object-fit: cover;
}

.avatar-info {
  padding: 12px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.avatar-name {
  font-size: 14px;
  color: #fff;
}

.right-panel {
  width: 400px;
  background: #23232a;
  border-radius: 16px;
  padding: 24px;
}

.preview-section h3 {
  margin: 0 0 20px;
  font-size: 18px;
  color: #fff;
}

.preview-container {
  background: #18181c;
  border-radius: 12px;
  height: 500px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 24px;
  overflow: hidden;
}

.upload-placeholder {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 12px;
  color: #909399;
  cursor: pointer;
  padding: 40px;
  width: 100%;
  height: 100%;
  justify-content: center;
  border: 2px dashed #2a2a2a;
  border-radius: 12px;
  transition: all 0.3s ease;
}

.upload-placeholder:hover {
  border-color: #409eff;
  background: #23232a;
}

.upload-text {
  font-size: 16px;
  margin-top: 12px;
}

.upload-hint {
  font-size: 12px;
  opacity: 0.7;
}

.preview-image {
  width: 100%;
  height: 100%;
  object-fit: contain;
}

.action-buttons {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

:deep(.el-tabs__header) {
  margin-bottom: 20px;
}

:deep(.el-tabs__nav-wrap) {
  padding: 0;
}

:deep(.el-tabs__nav) {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
  padding: 12px;
}

:deep(.el-tabs__item) {
  height: 36px;
  line-height: 36px;
  padding: 0 20px !important;
  border-radius: 18px;
  background: #23232a;
  border: 1px solid #2a2a2a;
  color: #909399 !important;
  margin: 0 !important;
}

:deep(.el-tabs__item:hover) {
  color: #fff !important;
  border-color: #409eff;
}

:deep(.el-tabs__item.is-active) {
  background: #409eff;
  border-color: #409eff;
  color: #fff !important;
}

:deep(.el-tabs__active-bar) {
  display: none !important;
}

:deep(.el-tabs__nav-scroll) {
  overflow: visible;
}

:deep(.el-tabs__nav-wrap::after) {
  display: none !important;
}

:deep(.el-button) {
  background: #23232a !important;
  border-color: #2a2a2a !important;
}

:deep(.el-button:hover) {
  background: #2a2a2a !important;
  border-color: #409eff !important;
}

:deep(.el-button--primary) {
  background: #409eff !important;
  border-color: #409eff !important;
}

:deep(.el-button--primary:hover) {
  background: #66b1ff !important;
  border-color: #66b1ff !important;
}

:deep(.el-button--danger) {
  background: #f56c6c !important;
  border-color: #f56c6c !important;
}

:deep(.el-button--danger:hover) {
  background: #f78989 !important;
  border-color: #f78989 !important;
}
</style> 